package com.wlm.service.impl;

import com.wlm.service.FileService;
import com.wlm.vo.ImageVO;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    // 定义本地磁盘的路径
    private String localDirPath = "E:/BaiduNetdiskDownload/jq-images";

    @Override
    public ImageVO upload(MultipartFile uploadFile) {

        // 获取图片的名称
        String fileName = uploadFile.getOriginalFilename();

        // 校验 正则表达式
        if (!fileName.matches("^.*\\.(jpg|png|gif)$")) {
            return ImageVO.fail();
        }

        // 校验恶意程序 图片：高度/宽度/px
        try {
            BufferedImage bImage = ImageIO.read(uploadFile.getInputStream());
            int width = bImage.getWidth();
            int height = bImage.getHeight();
            if (width == 0 || height == 0) {
                return ImageVO.fail();
            }

            // 实现分文件存储 yyyy/MM/dd/
            String dateDir = new SimpleDateFormat("yyyy/MM/dd/").format(new Date());
            String dirFilePath = localDirPath + dateDir;
            File dirFile = new File(dirFilePath);
            // 如果文件不存在，需要创建目录
            if (!dirFile.exists()) {
                dirFile.mkdirs();
            }

            // 动态生成文件名称 uuid + 文件后缀
            String uuid = UUID.randomUUID().toString();
            String fileType = fileName.substring(fileName.lastIndexOf("."));
            String realFilePath = uuid + fileType;
            uploadFile.transferTo(new File( realFilePath));

            // 实现数据的回显
            String url = "https://img14.360buyimg.com/n0/jfs/t1/165506/18/16048/121018/605d357fEca80b676/2d4ad31028381d05.jpg";

            ImageVO  imageVO = new ImageVO(0,url,width,height);
            return imageVO;
        } catch (Exception e) {
            e.printStackTrace();
            return ImageVO.fail();
        }
    }
}
